import React, { useState } from 'react';
import { LockOutlined, UserOutlined, MailOutlined, UserAddOutlined } from '@ant-design/icons';
import { Button, Form, Input, message, Flex } from 'antd';
import { Link, useNavigate } from 'react-router-dom';
import { register } from '../../api/auth';
import './Auth.css';

/**
 * 注册表单组件
 * @param {Object} props
 * @param {Function} props.onSuccess - 注册成功回调
 * @returns {React.ReactNode}
 */
const RegisterForm = ({ onSuccess }) => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const onFinish = async (values) => {
    try {
      setLoading(true);
      
      // 确认密码在前端验证，不需要发送到后端
      const { confirmPassword: _confirmPassword, ...registerData } = values;
      
      const response = await register(registerData);
      
      message.success('注册成功，请登录');
      
      // 调用成功回调或跳转到登录页
      if (onSuccess) {
        onSuccess(response.data);
      } else {
        navigate('/login');
      }
    } catch (error) {
      console.error('注册失败:', error);
      message.error(error.response?.data?.message || '注册失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className='register-form-container'>
      <div className='register-form-header'>
        <h2>用户注册</h2>
        <p>创建您的人力资源管理系统账号</p>
      </div>
      
      <Form
        form={form}
        name="register"
        onFinish={onFinish}
        className='register-form'
        scrollToFirstError
      >
        <Form.Item
          name="username"
          rules={[
            { required: true, message: '请输入用户名!' },
            { min: 4, message: '用户名至少4个字符' },
            { max: 20, message: '用户名最多20个字符' },
            { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' }
          ]}
        >
          <Input 
            prefix={<UserOutlined />} 
            placeholder="用户名" 
            size="large"
          />
        </Form.Item>
        
        <Form.Item
          name="name"
          rules={[{ required: true, message: '请输入姓名!' }]}
        >
          <Input 
            prefix={<UserAddOutlined />} 
            placeholder="姓名" 
            size="large"
          />
        </Form.Item>
        
        <Form.Item
          name="email"
          rules={[
            { required: true, message: '请输入邮箱!' },
            { type: 'email', message: '请输入有效的邮箱地址!' }
          ]}
        >
          <Input 
            prefix={<MailOutlined />} 
            placeholder="邮箱" 
            size="large"
          />
        </Form.Item>
        
        <Form.Item
          name="password"
          rules={[
            { required: true, message: '请输入密码!' },
            { min: 6, message: '密码至少6个字符' }
          ]}
          hasFeedback
        >
          <Input.Password 
            prefix={<LockOutlined />} 
            placeholder="密码" 
            size="large"
          />
        </Form.Item>
        
        <Form.Item
          name="confirmPassword"
          dependencies={['password']}
          hasFeedback
          rules={[
            { required: true, message: '请确认密码!' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次输入的密码不一致!'));
              },
            }),
          ]}
        >
          <Input.Password 
            prefix={<LockOutlined />} 
            placeholder="确认密码" 
            size="large"
          />
        </Form.Item>

        <Form.Item>
          <Button 
            type="primary" 
            htmlType="submit" 
            block 
            size="large"
            loading={loading}
          >
            注册
          </Button>
        </Form.Item>
        
        <Form.Item>
          <Flex justify="center">
            <span>已有账号？</span>
            <Link to="/login">立即登录</Link>
          </Flex>
        </Form.Item>
      </Form>
    </div>
  );
};

export default RegisterForm;